package net.huashitong.synthetical.newSupervision.controller;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.filter.SysUserLoginFilter;
import com.sirdc.modules.sys.service.DeptService;
import com.sirdc.modules.sys.service.SysDeptService;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.sys.util.UserUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.synthetical.newSupervision.entity.TaskBack;
import net.huashitong.synthetical.newSupervision.entity.TaskMessage;
import net.huashitong.synthetical.newSupervision.entity.TaskNew;
import net.huashitong.synthetical.newSupervision.entity.TaskSend;
import net.huashitong.synthetical.newSupervision.filter.TaskMessageFilter;
import net.huashitong.synthetical.newSupervision.filter.TaskNewFilter;
import net.huashitong.synthetical.newSupervision.service.TaskBackService;
import net.huashitong.synthetical.newSupervision.service.TaskMessageService;
import net.huashitong.synthetical.newSupervision.service.TaskNewService;
import net.huashitong.synthetical.newSupervision.service.TaskSendService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/7/16
 * Time: 18:55
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Controller
@RequestMapping("/message")
public class TaskMessageController extends JsonBaseController {
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private TaskNewService taskNewService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TaskBackService taskBackService;
    @Autowired
    private TaskMessageService taskMessageService;

    @Autowired
    private TaskSendService taskSendService;
    @Autowired
    private DeptService deptService;

    @Override
    protected String getView(String s) {
        return "/modules/project/message/" + s;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initPage() {
        return getView("query");
    }

    @RequestMapping("/filter")
    public String filter() {
        return getView("filter");
    }


    /**
     * 查询当前用户的消息
     *
     * @param filter
     * @return state
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid message(@ModelAttribute TaskMessageFilter filter) {
        //如果未传消息状态,默认查询未读消息
        if (StringUtils.isBlank(filter.getState())) {
            filter.setState("0");
        }
        //查询所有消息
        if ("2".equals(filter.getState())) {
            filter.setState("");
        }
     //查询当前用户所负责的项目
        String userId = SysUserUtils.getUserId();
    /*    SysLogin login = sysLoginService.getById(userId);
        String deptId = login.getDeptId();
        SysDept dept = sysDeptService.getById(deptId);
        List<TaskNew> projectList = new ArrayList<>();
        TaskNewFilter taskNewFilter = new TaskNewFilter();
        if ("01".equals(login.getRoleId())) {
            taskNewFilter.setInspectionId(deptId);
            projectList = taskNewService.getProjectList(taskNewFilter);
        } else {
            taskNewFilter.setOperatorId(userId);
            projectList = taskNewService.getProjectList(taskNewFilter);
        }
        //遍历当前用户所有的任务.取出每条任务的消息
        List<TaskMessage> list = new ArrayList<>();
        for (TaskNew taskNew : projectList) {
            filter.setTaskId(taskNew.getSysId());
            List<TaskMessage> messageList = taskMessageService.queryFilter(filter);
            list.addAll(messageList);
        }

        //按sysid降序排列
        Collections.sort(list, new Comparator<TaskMessage>() {
            @Override
            public int compare(TaskMessage o1, TaskMessage o2) {
                return o2.getSysId().compareTo(o1.getSysId());
            }
        });*/
      filter.setAccepterId(userId);
        List<TaskMessage> list = taskMessageService.queryFilter(filter);
        return coverJqGrid(filter, list);
    }


    /**
     * 信息详情
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail/{id}")
    public String messageInfo(Model model, @PathVariable String id) {
        TaskMessage message = taskMessageService.getById(id);
        model.addAttribute("message", message);
        return getView("detail");
    }


    /**
     * 返回督查组填写反馈结果
     *
     * @param model
     * @param id    信息id
     * @return
     */
    @RequestMapping(value = "/backResult/{id}", method = RequestMethod.GET)
    public String backResult(Model model, @PathVariable String id) {
        TaskMessage message = taskMessageService.getById(id);
        //如果督查人员打开信息反馈,改变消息为已读
        message.setState("1");//设置消息已读
        taskMessageService.update(message);

        TaskBack taskBack = taskBackService.getById(message.getBackId());

        Map<String, Object> map = new HashMap<>();

        map.put("message", message);
        map.put("taskBack", taskBack);
        //反馈列表
        model.addAttribute("map", map);
        //信息内容
        return getView("backResult");
    }

    /**
     * 更新反馈信息
     *
     * @param taskBack
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/backResult", method = RequestMethod.POST)
    public Message backResult(@ModelAttribute TaskBack taskBack) {

        String result = taskBackService.updateBack(taskBack);
        if ("200".equals(result)) {
            return coverMessage("200");
        } else {
            return coverMessage("500");
        }
    }


    /**
     * 处理申请协调/撤销页面
     *
     * @param model
     * @param id    消息id
     * @return
     */
    @RequestMapping(value = "/dispose/{id}")
    public String dispose(Model model, @PathVariable String id) {
        TaskMessage message = taskMessageService.getById(id);
        //改变消息已读状态
        message.setState("1");
        taskMessageService.update(message);

        TaskSend taskSend = taskSendService.getById(message.getSendId());
        TaskNew taskNew = taskNewService.getById(message.getTaskId());
        Map map = new HashMap<String, Object>();
        map.put("taskNew", taskNew);
        map.put("taskSend", taskSend);
        map.put("message", message);
        model.addAttribute("map", map);
        return getView("dispose");
    }

    /**
     * 处理申请撤销或者协调单位功能
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/dispose", method = RequestMethod.POST)
    public Message dispose(@ModelAttribute TaskMessageFilter filter) {
        String result = taskSendService.saveDispose(filter);
        if ("200".equals(result)) {
            return coverMessage("200");
        } else {
            return coverMessage("500");
        }
    }

    /**
     * 处理撤销操作,删除该单位的任务
     *
     * @param id 当前派送任务的主键
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteSend", method = RequestMethod.GET)
    public Message deleteSend(String id) {
        taskSendService.deleteSend(id);
        return coverMessage("200");
    }

    /**
     * 批量删除消息
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteMessage/{ids}")
    public Message deleteMessage(@PathVariable List<String> ids) {
        taskMessageService.batchDelete(ids);
        return coverMessage("200");
    }

    /**
     * 返回所有乡镇单位列表,以及单位管理员userid;
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deptList", method = RequestMethod.POST)
    public List<Map<String, String>> deptList() {
        List<SysDept> list = deptService.queryDeptList("/02/");
        List<Map<String, String>> mapList = new ArrayList<>();
        Map<String, String> map = null;
        for (SysDept sysDept : list) {
            String deptName = sysDept.getDeptName();
            String deptRelation = sysDept.getDeptRelation() + sysDept.getDeptId() + "/";
            map = new HashMap<>();
            map.put("deptName", deptName);
            map.put("deptRelation", deptRelation);
            mapList.add(map);
        }
        return mapList;
    }


    /**
     * 返回最后一级单位列表,以及单位管理员userId;
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/childDeptList", method = RequestMethod.POST)
    public List<Map<String, String>> childDeptList(String deptRelation) {
        List<SysDept> deptList = deptService.queryDeptList(deptRelation);
        List<Map<String, String>> list = new ArrayList<>();
        for (SysDept dept : deptList) {
            Map<String, String> map = new HashMap<>();
            String deptName = dept.getDeptName();
            String sysId = dept.getSysId();
            SysUserFilter sysUserFilter = new SysUserFilter();
            sysUserFilter.setDeptId(sysId);
            sysUserFilter.setRoleId("01");
            List<SysLogin> sysLoginList = sysLoginService.queryUserLoginByRoleDept(sysUserFilter);
            if (sysLoginList.size() > 0) {
                map.put("deptName", deptName);
                map.put("userId", sysLoginList.get(0).getSysId());
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 打开转发页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/forwardTo/{id}")
    public String forwardTo(Model model, @PathVariable String id) {
        String userId = SysUserUtils.getUserId();
        String deptId = SysUserUtils.getDeptId();
        SysDept dept = deptService.getById(deptId);
        TaskMessage message = taskMessageService.getById(id);
        SysUserFilter filter = new SysUserFilter();
        List<SysUser> list = new ArrayList<>();
        //如果当前用户是督查组
        if ("/01/".equals(dept.getDeptRelation())){
            //批转对象为政府办副主任,设置单位为政府办
            String forwardUserId="20190802100000000229";
            SysUser user = sysUserService.getById(forwardUserId);
            list.add(user);
            model.addAttribute("list", list);
        }else if("20190802100000000229".equals(userId)){
            //如果是副主任,批转给主任
            String  forwardUserId="20190802100000000228";
            SysUser user = sysUserService.getById(forwardUserId);
            list.add(user);
            model.addAttribute("list", list);
        }else if ("20190802100000000228".equals(userId)){
            //如果是主任,批转给主官
            filter.setDeptId("20190802100000000091");
            List<SysLogin> sysLoginList = sysLoginService.queryUserLoginByRoleDept(filter);
            for (SysLogin sysLogin : sysLoginList) {
                SysUser user = sysUserService.getById(sysLogin.getSysId());
                list.add(user);
            }
            model.addAttribute("list", list);
        }
        model.addAttribute("message", message);
        return getView("forwardTo");
    }

    /**
     * 转发消息到上级
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/forwardTo", method = RequestMethod.POST)
    public Message forwardTo(TaskMessageFilter filter) {
        //取出原来的消息
        TaskMessage message = taskMessageService.getById(filter.getSysId());
        //新建一条新的消息
        TaskMessage taskMessage = new TaskMessage();
        //原来的消息复制发送给新的消息接收人
        BeanUtils.copyProperties(message, taskMessage);
        taskMessage.setAccepterId(filter.getAccepterId());
        taskMessage.setSenderId(SysUserUtils.getUserId());
        taskMessage.setState("0");
        taskMessageService.save(taskMessage);
        return coverMessage("200");
    }
}
